package com.inwavetech.os.util;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by jgskin on 1/30/14.
 */
public class Form {

    private final HashMap<String, EditText> fields;
    private final Button submit;
    private final Activity context;
    private final UrlBuilderInterface urlBuilder;
    private final LoaderAnimation loaderAnimation;
    private final ResponseHandlerInterface responseHandler;

    public Form(Activity context, LoaderAnimation loaderAnimation, HashMap<String, EditText> fields,
                Button submit, Form.UrlBuilderInterface urlBuilder, ResponseHandlerInterface responseHandler) {
        this.context = context;
        this.fields = fields;
        this.submit = submit;
        this.urlBuilder = urlBuilder;
        this.loaderAnimation = loaderAnimation;
        this.responseHandler = responseHandler;

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Send().execute();
            }
        });
    }

    public interface UrlBuilderInterface {
        public String build();
    }

    public interface ResponseHandlerInterface {
        public void handle(SimpleResponse response);
    }

    private class Send extends AsyncTask<String, String, SimpleResponse> {

        @Override
        protected void onPreExecute() {
            loaderAnimation.toggle();
        }

        @Override
        protected SimpleResponse doInBackground(String... params) {
            StrictMode.ThreadPolicy mThreadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(mThreadPolicy);

            ArrayList<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();

            Iterator it = fields.entrySet().iterator();
            while (it.hasNext()) {
                HashMap.Entry pairs = (HashMap.Entry) it.next();

                String paramName = (String) pairs.getKey();
                EditText view = (EditText) pairs.getValue();

                postParams.add(new BasicNameValuePair(paramName, view.getText().toString()));
            }

            return new Request().post(urlBuilder.build(), postParams);
        }

        @Override
        protected void onPostExecute(SimpleResponse response) {
            loaderAnimation.toggle();
            responseHandler.handle(response);
        }

    }
}
